package com.doget.data.web;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.doget.data.R;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Map;


public class WebActivity extends AppCompatActivity {

    WebView webView;
    private RelativeLayout headView;
    private TextView tvTitle;
    private ImageView ivBack;
    private ImageView ivShare;
    private ImageView ivToHome;
    private String shareTitle = "";
    private String mTitle = "";
    private SmartRefreshLayout refreshLayout;
    // public static String mCurPicPath  = "";

    String url;
    String picUrl;
    private String pageFinishedUrl = "";
    private boolean enablePageFinishedUrl = false;

    public static void goTo(Context context, String url, boolean isShowTitle, boolean isShowShare, String title) {
        Intent intent = new Intent(context, WebActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("is_show_title", isShowTitle);
        intent.putExtra("is_show_share", isShowShare);
        intent.putExtra("title", title);
        context.startActivity(intent);
    }

    public static void goTo(Context context, String url, boolean isShowTitle, boolean isShowShare, String title, boolean isShowHomeAction) {
        Intent intent = new Intent(context, WebActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("is_show_title", isShowTitle);
        intent.putExtra("is_show_share", isShowShare);
        intent.putExtra("title", title);
        intent.putExtra("is_show_home_action", isShowHomeAction);
        context.startActivity(intent);
    }

    public static void goTo(Context context, String url, boolean isShowTitle, boolean isShowShare, boolean whiteTitle, String title) {
        Intent intent = new Intent(context, WebActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("is_show_title", isShowTitle);
        intent.putExtra("is_show_share", isShowShare);
        intent.putExtra("title_white", whiteTitle);
        intent.putExtra("title", title);
        context.startActivity(intent);
    }

    @SuppressLint("JavascriptInterface")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
        Intent intent = getIntent();
        url = intent.getStringExtra("url");

        String eventName = null;
        if (url.contains("pages/goods/index")) {
            eventName = "普通商品";
        } else if (url.contains("pages/sharing/goods/index")) {
            eventName = "团购商品";
        } else if (url.contains("pages/bargain/goods/index")) {
            eventName = "砍价商品";
        } else if (url.contains("pages/seckill/goods/index")) {
            eventName = "秒杀商品";
        }

        if (eventName != null)
            //JPushEventUtils.postJPushEvent(eventName);

        Log.d("ck--", url);
        boolean isShowTitle = intent.getBooleanExtra("is_show_title", false);
        boolean isShowShare = intent.getBooleanExtra("is_show_share", false);
        boolean isWhiteTitle = intent.getBooleanExtra("title_white", false);
        boolean isShowHomeAction = intent.getBooleanExtra("is_show_home_action", false);

        headView = findViewById(R.id.head_view);
        tvTitle = findViewById(R.id.headerTitle);
        ivShare = findViewById(R.id.iv_share);
        ivBack = findViewById(R.id.iv_back);
        ivToHome = findViewById(R.id.iv_to_home);
        refreshLayout = findViewById(R.id.refresh_layout);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setRefreshHeader(new MaterialHeader(this));
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (!TextUtils.isEmpty(url)) {
                    webView.reload();
                }
            }
        });
        //是否展示回首页的图标
        if (isShowHomeAction) {
            ivToHome.setVisibility(View.VISIBLE);
            ivToHome.setOnClickListener(v -> {
                if (webView != null) {
                    webView.destroy();
                }
                finish();
            });
        } else {
            ivToHome.setVisibility(View.GONE);
        }

        ivShare.setOnClickListener(v -> {
            dismissDialog();
            String shareUrl = webView.getUrl();
            shareTitle = webView.getTitle();

        });
        if (isShowTitle) {

        }
        if (isShowShare) {
            ivShare.setVisibility(View.VISIBLE);
        } else {
            ivShare.setVisibility(View.GONE);
        }

        mTitle = getIntent().getStringExtra("title");

        tvTitle.setText(mTitle);
        headView.setVisibility(isShowTitle ? View.VISIBLE : View.GONE);
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(v -> onBackPressed());
        webView = findViewById(R.id.webContainer);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setDisplayZoomControls(false);
        webSettings.setSupportZoom(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        webSettings.setBlockNetworkImage(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        //解除数据阻止
        webSettings.setBlockNetworkImage(false);
        // 设置字符集编码
        webSettings.setDefaultTextEncodingName("UTF-8");
        getWindow().setFormat(PixelFormat.TRANSLUCENT);

        webView.addJavascriptInterface(new CommonJsInterface(this, new CommonJsInterface.WebviewCallbackListerner() {
            @Override
            public void weAppPayCallback(String str) {
                if (TextUtils.isEmpty(str))
                    str = "";
                String path = "pages/pay-estore/pay-estore?payJsonParams=" + str;

            }

            @Override
            public void askShare(String title, String imageUrl, String webUrl, String shareGroupUrl) {

            }

            @Override
            public void doClose() {
                finish();
            }

            @Override
            public void startScanner() {

            }

            @Override
            public void setTitle(String title) {
                tvTitle.setText(title);
            }

            @Override
            public void goToBillPay() {
//                ARouter.getInstance().build("/activity/bill/choose/houses").withString("goToPath", BillChooseHouseActivity.GO_TO_BILL_PAY).navigation();
            }

            @Override
            public void goToAutoPay() {
//                ARouter.getInstance().build("/activity/bill/choose/houses").withString("goToPath", BillChooseHouseActivity.GO_TO_AUTO_PAY).navigation();
            }

            @Override
            public void goToWXMimi(String param) {
//                WebGoToWXMiniBean bean = GsonHelper.fromJson(param, WebGoToWXMiniBean.class);
//                if (bean != null) {
//                    //欧普小程序
//                    if (TextUtils.equals(bean.getType(), "1")) {
//                        PaymentUtil.launchWXMiniById(WebActivity.this, "gh_0df2250b9e74", "pages/appoint/appoint?orderId=" + bean.getOrderId());
//                    }
//                }

            }

            @Override
            public void publicGoToWXMimi(String param) {
//                    PaymentUtil.launchWXMiniByIdCH(WebActivity.this, "gh_e10f5dcc0cd5", param );
            }

            @Override
            public void goToPage(String json) {
//                WebGoToPageBean bean = GsonHelper.fromJson(json, WebGoToPageBean.class);
//                if (bean != null) {
//                    if (TextUtils.equals(bean.getPage(), "insideRepair")) {
//                        ARouter.getInstance().build("/activity/new/inside/repair").withString("orderId", bean.getOrderId()).navigation();
//                    }
//                }
            }

            @Override
            public void callUmengEvent(String eventId) {
                //JPushEventUtils.postJPushEventById(eventId, "");

//                Consts.gotoEvent( eventId);
            }

            @Override
            public void fromOnlineShoppingMallLogin(String param) {
//                H5LoginiBean bean = GsonHelper.fromJson(param, H5LoginiBean.class);
//                if (null == bean || null == bean.getUrl() || bean.getUrl().length() < 1) {
//                } else {
//                    pageFinishedUrl = bean.getUrl();
//                }
//                enablePageFinishedUrl = true;
//                ARouter.getInstance().build(ARouterUtils.PWD_LOGIN).withString("h5gotoPwdLogin", pageFinishedUrl).navigation();

//                //JPushEventUtils.postJPushEventById(eventId, "");
            }

            @Override
            public void onlineShoppingMallEvent(String key, String json) {
//                String account = SPUtil.getInstance().getValue(Consts.SPKeys.LoginUserAccount);
//                if (null == json || json.equals("") || json.equals("undefined")) {
//                    Consts.gotoEvent(   key);
//                } else {
//                    Map map = JSONObject.parseObject(json, Map.class);
//                    Consts.gotoEvent(   key, map);
//                }
            }
        }), "AndroidWebView");


//        webView.setOnKeyListener((v, keyCode, event) -> {
//            if (event.getAction() == KeyEvent.ACTION_DOWN) {
//                if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
//                    webView.goBack();   //后退
//                    return true;    //已处理
//                }
//            }
//            return false;
//        });

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                Log.d("webView_url", "onReceivedTitle:" + view.getUrl());
                if (title.length() > 10) {
                    title = title.substring(0, 10) + "...";
                }
                if (webView.canGoBack()) {
                    tvTitle.setText(title);
                } else {
                    tvTitle.setText(TextUtils.isEmpty(mTitle) ? title : mTitle);
                }
                if (url.contains("record") || url.contains("shopTrolley")) {
                    ivShare.setVisibility(View.GONE);
                } else {
                    if (isShowShare) {
                        ivShare.setVisibility(View.VISIBLE);
                    } else {
                        ivShare.setVisibility(View.GONE);
                    }
                }
                super.onReceivedTitle(view, title);
            }
        });
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.d("webView_url", "shouldOverrideUrlLoading:" + url);
                refreshLayout.setEnableRefresh(true);
                if (url.startsWith("alipays:") || url.startsWith("alipay")) {
                    try {
                        startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url)));
                    } catch (Exception e) {
                    }
                    return true;
                } else if (url.startsWith("weixin://wap/pay?")) {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    startActivity(intent);
                    return true;
                } else if (url.contains("newMeeting/#/")) {
                    //解决滑动冲突
                    refreshLayout.setEnableRefresh(false);
                }
                return false;
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
//     注意：super句话一定要删除，或者注释掉，否则又走handler.cancel() 默认的不支持https的了。
//     super.onReceivedSslError(view, handler, error);
                handler.proceed();// 接受所有网站的证书
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                Log.d("webView_url", "onPageFinished:" + url);
                pageFinishedUrl = url;
                String title = view.getTitle();
                if (title.length() > 10) {
                    title = title.substring(0, 10) + "...";
                }
                if (webView.canGoBack()) {
                    tvTitle.setText(title);
                } else {
                    tvTitle.setText(TextUtils.isEmpty(mTitle) ? title : mTitle);
                }
                if (url.contains("record") || url.contains("shopTrolley")) {
                    ivShare.setVisibility(View.GONE);
                } else {
                    if (isShowShare) {
                        ivShare.setVisibility(View.VISIBLE);
                    } else {
                        ivShare.setVisibility(View.GONE);
                    }
                }
                refreshLayout.finishRefresh();
                super.onPageFinished(view, url);
            }
        });

        // 长按点击事件
        webView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                final WebView.HitTestResult hitTestResult = webView.getHitTestResult();
                // 如果是图片类型或者是带有图片链接的类型
                if (hitTestResult.getType() == WebView.HitTestResult.IMAGE_TYPE ||
                        hitTestResult.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
                    // 弹出保存图片的对话框
                    AlertDialog.Builder builder = new AlertDialog.Builder(WebActivity.this);
                    builder.setTitle("提示");
                    builder.setMessage("保存图片到本地");
                    builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            picUrl = hitTestResult.getExtra();//获取图片链接
                            //保存图片到相册
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    if (picUrl.startsWith("http") || picUrl.startsWith("HTTP"))
                                        url2bitmap(picUrl);
                                    else
                                        saveImage(picUrl);
                                }
                            }).start();
                        }
                    });
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        // 自动dismiss
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                        }
                    });
                    AlertDialog dialog = builder.create();
                    dialog.show();
                    return true;
                }
                return false;//保持长按可以复制文字
            }
        });
        Log.d("webView_url", "loadUrl:" + url);
        webView.loadUrl(url);
    }

    public void saveImage(String data) {
        try {
            Bitmap bitmap = webData2bitmap(data);
            if (bitmap != null) {
                save2Album2(bitmap, new SimpleDateFormat("SXS_yyyyMMddHHmmss", Locale.getDefault()).format(new Date()) + ".jpg");
            } else {
                runOnUiThread(() -> Toast.makeText(WebActivity.this, "保存失败", Toast.LENGTH_SHORT).show());
            }
        } catch (Exception e) {
            runOnUiThread(() -> Toast.makeText(WebActivity.this, "保存失败", Toast.LENGTH_SHORT).show());
            e.printStackTrace();
        }
    }

    public Bitmap webData2bitmap(String data) {
        byte[] imageBytes = Base64.decode(data.split(",")[1], Base64.DEFAULT);
        return BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
    }

    private void save2Album2(Bitmap bitmap, String fileName) {
        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), fileName);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
            runOnUiThread(() -> {
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
                Toast.makeText(WebActivity.this, "保存成功", Toast.LENGTH_SHORT);
            });
        } catch (Exception e) {
            runOnUiThread(() -> Toast.makeText(WebActivity.this, "保存失败", Toast.LENGTH_SHORT));
            e.printStackTrace();
        } finally {
            try {
                fos.close();
            } catch (Exception ignored) {
            }
        }
    }

    public void url2bitmap(String url) {
        Bitmap bm = null;
        try {
            URL iconUrl = new URL(url);
            URLConnection conn = iconUrl.openConnection();
            HttpURLConnection http = (HttpURLConnection) conn;
            int length = http.getContentLength();
            conn.connect();
            // 获得图像的字符流
            InputStream is = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is, length);
            bm = BitmapFactory.decodeStream(bis);
            bis.close();
            is.close();
            if (bm != null) {
                save2Album2(bm, new SimpleDateFormat("SXS_yyyyMMddHHmmss", Locale.getDefault()).format(new Date()) + ".jpg");
//                save2Album(bm);
            }
        } catch (Exception e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(WebActivity.this, "保存失败", Toast.LENGTH_SHORT).show();
                }
            });
            e.printStackTrace();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == SimpleScannerActivity.REQUEST_CODE && resultCode == SimpleScannerActivity.RESULT_CODE) {
//            String result = "";
//            if (data != null) {
//                result = data.getStringExtra("result");
//                //Log.i(("ck--", "拿到数据" + data.getStringExtra("result"));
//            }
//            String url = "javascript:handleScanResult" + "('" + result + "')";
//            webView.loadUrl(url);
//        }
    }

    @Override
    public void onBackPressed() {

        if (url.contains("epidemic.html")) {
            finish();
            return;
        }

        if (webView != null && webView.canGoBack()) {
            webView.goBack();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onDestroy() {
        if (webView != null) {
            webView.clearCache(true);
            webView.clearHistory();
            webView.clearFormData();
            webView.destroy();
            webView = null;
        }
        dismissDialog();
        super.onDestroy();
    }

    private void dismissDialog() {

    }

//    @Override
//    public void onResume() {
//        super.onResume();
//        String phone = Consts.LoginUserPhone;
//        String secretAccount = Consts.getSecretAccount;
//        if (phone.equals("") || secretAccount.equals("")) {
//            return;
//        }
//        if (null == pageFinishedUrl || pageFinishedUrl.equals("") ) return;
//        pageFinishedUrl = pageFinishedUrl + "&mobile=" + phone + "&secretAccount=" + secretAccount;
////        Log.i("onResume====", "onResume: " + pageFinishedUrl);
//        if (enablePageFinishedUrl) {
//            if (null == webView) return;
//            webView.loadUrl(pageFinishedUrl);
//            enablePageFinishedUrl = false;
//        }
//
//    }
}